# Copyright 2010 Mikko Rantanen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
import simplejson as json
import uuid
import os
import re
import bus

class Channel():
    
    def __init__(self, vaultpath):
        vaultpath = os.path.abspath(vaultpath)
        self.buspath = vaultpath + "/.mfilesfs"

        if not os.path.isdir(self.buspath):
            raise IOError

        self.cname = uuid.uuid1().hex
        self.cpath = os.path.join(self.buspath, self.cname)
        self.channel = open(self.cpath, 'r+')
        self.replies = {}

    def __enter__(self):
        return self

    def __exit__(self, r,n,d):
        self.close()

    def close(self):
        self.channel.close()

    def write(self, cmd, param, sync = False):
        msg_id = uuid.uuid1().hex
        self.channel.write("%s,%s,%s\n" % (cmd, msg_id, json.dumps(param)))
        if not sync:
            return msg_id
        else:
            return self.read(msg_id)
        
    def read(self, msg_id):
        if msg_id in self.replies:
            return processresult(*self.replies[msg_id])

        while 1:
            self.channel.seek(0)
            line = self.channel.readline()
            m = re.match('(?P<id>[^,]*),\s*(?P<status>success|error)\s*,(?P<result>.*)', line)

            assert m, "Malformed message"

            read_id = m.group('id').strip()
            status = m.group('status')
            result = m.group('result').strip()
            
            if read_id == msg_id:
                return self.processresult(status, result)
            
            self.replies[read_id] = (status, result)

    def processresult(self, status, result):
        result = json.loads(result)
        if status == "success":
            return result
        elif status == "error":
            raise bus.BusError(*result)

